package com.auto.autoapp.services

import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.provider.Settings
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import android.animation.ValueAnimator
import android.view.animation.DecelerateInterpolator
import com.auto.autoapp.R
import com.auto.autoapp.task.GetDyCodeTask
import com.auto.autoapp.task.getNodeTestTask
import com.ven.assists.service.AssistsService
import com.ven.assists.stepper.StepManager
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.sqrt

class FloatingWindowService : Service() {
    
    companion object {
        private const val TAG = "FloatingWindowService"
        private var instance: FloatingWindowService? = null
        
        fun getInstance(): FloatingWindowService? = instance
        
        fun addLog(message: String) {
            instance?.addLogMessage(message)
        }
    }
    
    private var windowManager: WindowManager? = null
    private var floatingView: View? = null
    private var isExpanded = false
    private var logTextView: TextView? = null
    private var scrollView: ScrollView? = null
    
    // 拖动相关变量
    private var windowParams: WindowManager.LayoutParams? = null
    private var initialX = 0
    private var initialY = 0
    private var initialTouchX = 0f
    private var initialTouchY = 0f
    private var isDragging = false
    private var dragThreshold = 10f // 拖动阈值，避免误触
    
    override fun onCreate() {
        super.onCreate()
        instance = this
        Log.d(TAG, "FloatingWindowService created")
    }
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent?.action == "SHOW_FLOATING_WINDOW") {
            showFloatingWindow()
        } else if (intent?.action == "HIDE_FLOATING_WINDOW") {
            hideFloatingWindow()
        }
        return START_STICKY
    }
    
    override fun onBind(intent: Intent?): IBinder? = null
    
    private fun showFloatingWindow() {
        if (floatingView != null) {
            Log.d(TAG, "Floating window already showing")
            return
        }
        
        if (!Settings.canDrawOverlays(this)) {
            Log.e(TAG, "Permission to draw over other apps not granted")
            return
        }
        
        windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
        
        val inflater = LayoutInflater.from(this)
        floatingView = inflater.inflate(R.layout.floating_window, null)
        
        setupFloatingWindow()
        setupClickListeners()
        setupDragListener()
        
        windowParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            },
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
        )
        
        val displayMetrics = resources.displayMetrics
        val screenWidth = displayMetrics.widthPixels
        val screenHeight = displayMetrics.heightPixels
        val ballSizePx = (48 * displayMetrics.density).toInt()
        
        windowParams?.gravity = Gravity.TOP or Gravity.START
        // 默认吸附右侧，距离顶部为屏幕高的 1/3
        windowParams?.x = screenWidth - ballSizePx
        windowParams?.y = screenHeight / 3
        
        windowManager?.addView(floatingView, windowParams)
        
        // 视图测量完成后，精确贴边到右侧（避免宽度估算误差）
        floatingView?.post {
            val params = windowParams ?: return@post
            val v = floatingView ?: return@post
            val vw = (v.width.takeIf { it > 0 } ?: v.measuredWidth.takeIf { it > 0 } ?: ballSizePx)
            params.x = screenWidth - vw
            windowManager?.updateViewLayout(v, params)
        }
        
        Log.d(TAG, "Floating window shown")
    }
    
    private fun setupFloatingWindow() {
        floatingView?.let { view ->
            logTextView = view.findViewById(R.id.tv_log)
            scrollView = view.findViewById(R.id.scroll_view)
            val logContainer = view.findViewById<LinearLayout>(R.id.log_container)
            val controlsContainer = view.findViewById<LinearLayout>(R.id.controls_container)
            val contentContainer = view.findViewById<LinearLayout>(R.id.content_container)
            
            // 初始状态为收起
            isExpanded = false
            
            // 默认隐藏内容容器与其子视图
            logContainer.visibility = View.GONE
            controlsContainer.visibility = View.GONE
            contentContainer.visibility = View.GONE
        }
    }
    
    private fun setupClickListeners() {
        floatingView?.let { view ->
            val btnExpand = view.findViewById<Button>(R.id.btn_expand)
            val btnCollapse = view.findViewById<Button>(R.id.btn_collapse)
            val btnClose = view.findViewById<Button>(R.id.btn_close)
            val btnClear = view.findViewById<Button>(R.id.btn_clear)
            val btnStop = view.findViewById<Button>(R.id.btn_stop)
            val floatingBall = view.findViewById<View>(R.id.floating_ball)
            btnStop.setOnClickListener {
                StepManager.isStop = true
            }
            
            floatingBall.setOnClickListener {
                if (isExpanded) collapseWindow() else expandWindow()
            }
            
            btnExpand.setOnClickListener { expandWindow() }
            btnCollapse.setOnClickListener { collapseWindow() }
            btnClear.setOnClickListener { clearLog() }
            btnClose.setOnClickListener { hideFloatingWindow() }
        }
    }

    private fun clearLog(){
        runOnUiThread {
           logTextView?.text = ""
        }
    }
    
    @SuppressLint("ClickableViewAccessibility")
    private fun setupDragListener() {
        floatingView?.let { view ->
            val dragArea = view.findViewById<View>(R.id.floating_ball)
            
            dragArea?.setOnTouchListener { v, event ->
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        initialX = windowParams?.x ?: 0
                        initialY = windowParams?.y ?: 0
                        initialTouchX = event.rawX
                        initialTouchY = event.rawY
                        isDragging = false
                        Log.d(TAG, "Touch DOWN for drag")
                        // 消耗事件以便后续 MOVE/UP 都由我们处理
                        true
                    }
                    MotionEvent.ACTION_MOVE -> {
                        val deltaX = event.rawX - initialTouchX
                        val deltaY = event.rawY - initialTouchY
                        val distance = sqrt(deltaX * deltaX + deltaY * deltaY)
                        
                        if (!isDragging && distance > dragThreshold) {
                            isDragging = true
                            Log.d(TAG, "Drag started")
                        }
                        
                        if (isDragging) {
                            windowParams?.x = initialX + deltaX.toInt()
                            windowParams?.y = initialY + deltaY.toInt()
                            
                            val displayMetrics = resources.displayMetrics
                            val screenWidth = displayMetrics.widthPixels
                            val screenHeight = displayMetrics.heightPixels
                            
                            val viewWidth = (floatingView?.width ?: 0).let { w -> if (w > 0) w else (floatingView?.measuredWidth ?: 200) }
                            val viewHeight = (floatingView?.height ?: 0).let { h -> if (h > 0) h else (floatingView?.measuredHeight ?: 200) }
                            
                            windowParams?.x = windowParams?.x?.coerceIn(0, screenWidth - viewWidth) ?: 0
                            windowParams?.y = windowParams?.y?.coerceIn(0, screenHeight - viewHeight) ?: 0
                            
                            windowManager?.updateViewLayout(floatingView, windowParams)
                        }
                        true
                    }
                    MotionEvent.ACTION_UP -> {
                        if (!isDragging) {
                            Log.d(TAG, "Click on floating ball")
                            v.performClick()
                        } else {
                            Log.d(TAG, "Drag ended at (${windowParams?.x}, ${windowParams?.y})")
                            if (!isExpanded) {
                                snapToEdge()
                            }
                        }
                        isDragging = false
                        true
                    }
                    else -> false
                }
            }
        }
    }
    
    private fun expandWindow() {
        if (isExpanded) return // 已经展开，不需要重复操作
        
        isExpanded = true
        animateViewChanges(true)
        Log.d(TAG, "Window expanded")
    }
    
    private fun collapseWindow() {
        if (!isExpanded) return // 已经收起，不需要重复操作
        
        isExpanded = false
        animateViewChanges(false)
        Log.d(TAG, "Window collapsed")
    }
    
    private fun animateViewChanges(expanding: Boolean) {
        floatingView?.let { view ->
            val btnExpand = view.findViewById<Button>(R.id.btn_expand)
            val btnCollapse = view.findViewById<Button>(R.id.btn_collapse)
            val btnClose = view.findViewById<Button>(R.id.btn_close)
            val logContainer = view.findViewById<LinearLayout>(R.id.log_container)
            val controlsContainer = view.findViewById<LinearLayout>(R.id.controls_container)
            val contentContainer = view.findViewById<LinearLayout>(R.id.content_container)
            
            val duration = 300L
            
            if (expanding) {
                // 展开：先显示内容容器
                contentContainer.visibility = View.VISIBLE
                
                logContainer.visibility = View.VISIBLE
                controlsContainer.visibility = View.VISIBLE
                logContainer.alpha = 0f
                controlsContainer.alpha = 0f
                logContainer.animate()
                    .alpha(1f)
                    .setDuration(duration)
                    .start()
                controlsContainer.animate()
                    .alpha(1f)
                    .setDuration(duration)
                    .withEndAction { updateWindowLayout() }
                    .start()
            } else {
                // 收起：淡出子视图，结束后隐藏内容容器
                logContainer.animate()
                    .alpha(0f)
                    .setDuration(duration)
                    .withEndAction {
                        logContainer.visibility = View.GONE
                        updateWindowLayout()
                    }
                    .start()
                controlsContainer.animate()
                    .alpha(0f)
                    .setDuration(duration)
                    .withEndAction {
                        controlsContainer.visibility = View.GONE
                        contentContainer.visibility = View.GONE
                        updateWindowLayout()
                        // 收起后自动吸边
                        floatingView?.post { if (!isExpanded) snapToEdge() }
                    }
                    .start()
            }
        }
    }
    
    private fun updateWindowLayout() {
        // 确保窗口管理器和参数不为空
        if (windowManager != null && windowParams != null && floatingView != null) {
            // 重新测量视图以获取正确的尺寸
            floatingView?.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            )
            
            // 更新窗口管理器的布局参数
            windowManager?.updateViewLayout(floatingView, windowParams)
        }
    }
    
    fun addLogMessage(message: String) {
        runOnUiThread {
            val timestamp = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
                .format(Date())
            val logMessage = "[$timestamp] $message\n"
            
            logTextView?.append(logMessage)
            
            // 自动滚动到底部
            scrollView?.post {
                scrollView?.fullScroll(View.FOCUS_DOWN)
            }
            
            Log.d(TAG, "Log added: $message")
        }
    }
    
    private fun runOnUiThread(action: Runnable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            action.run()
        } else {
            Handler(Looper.getMainLooper()).post(action)
        }
    }
    
    private fun hideFloatingWindow() {
        StepManager.isStop = true
        floatingView?.let {
            windowManager?.removeView(it)
            floatingView = null
            Log.d(TAG, "Floating window hidden")
        }
        
        // 停止服务，确保服务被销毁
        stopSelf()
        Log.d(TAG, "Service stopping after hiding floating window")
    }
    
    override fun onDestroy() {
        super.onDestroy()
        hideFloatingWindow()
        instance = null
        Log.d(TAG, "FloatingWindowService destroyed")
    }

    private fun snapToEdge() {
        val wm = windowManager ?: return
        val params = windowParams ?: return
        val view = floatingView ?: return

        val screenWidth = resources.displayMetrics.widthPixels
        val viewWidth = (view.width.takeIf { it > 0 } ?: view.measuredWidth.takeIf { it > 0 } ?: 200)
        val currentX = params.x

        val leftX = 0
        val rightX = screenWidth - viewWidth
        val targetX = if (currentX + viewWidth / 2 < screenWidth / 2) leftX else rightX

        if (currentX == targetX) return

        ValueAnimator.ofInt(currentX, targetX).apply {
            duration = 180
            interpolator = DecelerateInterpolator()
            addUpdateListener { va ->
                params.x = va.animatedValue as Int
                wm.updateViewLayout(view, params)
            }
            start()
        }
    }
}
